<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // 接雨水
    //计算出每个柱子能接多少水
    //Math.min(l_max,r_max)-height[i]
    let height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
    //let height = [4, 2, 0, 3, 2, 5]
    var trap = function (height) {
        if (height.length === 0) return 0
        let n = height.length
        let res = 0
        let l_max = new Array(n)
        let r_max = new Array(n)
        l_max[0] = height[0]
        r_max[n - 1] = height[n - 1]
        //左边最高
        for (let i = 1; i < n; i++) {
            l_max[i] = Math.max(height[i], l_max[i - 1])

        }
        //右边最高
        for (let j = n - 2; j >= 0; j--) {
            r_max[j] = Math.max(height[j], r_max[j + 1])

        }
        //相加
        for (let i = 0; i < n; i++) {
            res += Math.min(l_max[i], r_max[i]) - height[i]
        }
        console.log(res, "=====");
        return res
    };
    trap(height)
</script>

</html>